package pl.lodz.p.browarex.validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import pl.lodz.p.browarex.model.OrderProductInfo;

@Component
public class OrderInfoValidator implements Validator {

	@Override
	public boolean supports(Class<?> type) {
		return type == OrderProductInfo.class;
	}

	@Override
	public void validate(Object target, Errors errors) {

		OrderProductInfo orderInfo = (OrderProductInfo) target;
		boolean isQuantityNotNull = true;
		if (orderInfo.getQuantity() == null) {
			isQuantityNotNull = false;
			errors.rejectValue("product.quantity", "order.quantity.null");
		}
		if (isQuantityNotNull) {
			if (orderInfo.getQuantity() > orderInfo.getProduct().getQuantity()) {
				errors.rejectValue("product.quantity", "order.quantity.error");
			}
			if (orderInfo.getQuantity() <= 0) {
				errors.rejectValue("product.quantity", "order.quantity.null");
			}

		}
	}

}
